package com.wuda;

import java.util.HashMap;
import java.util.Map;

/**
 * 无词典分词算法
 * 
 * @author wuda
 * @version JDK1.7
 * 
 */
public class NonDicSegment {

	/**
	 * 
	 * @param input
	 *            输入字符串
	 * @return 关键词-格式为：<i>Map</i>的<i>key</i>为关键词名称,<i>value</i>为这个关键词的频率
	 */
	public Map<String, Integer> getKeywords(String input) {
		char[] charArray = input.toCharArray();

		Map<String, Integer> words = new HashMap<String, Integer>();

		int length = charArray.length;
		int currentIndex = 0;
		Character currentChar = null;
		Character currentCharNext = null;// 与当前字符紧邻的字符,不光只是紧邻的第一个,也有可能是紧邻的第2个,3个...
		Character tmpChar = null;
		Character tmpCharNext = null;

		int word_width;
		boolean nextCharEquals = true;
		StringBuilder word = null;

		String _word = null;

		while (currentIndex < length) {
			currentChar = charArray[currentIndex];// 取出当前的字符
			if (CommonConfig.PUNCTUATIONS.indexOf(currentChar) != -1) {// 标点符号
				currentIndex++;
				continue;
			}
			word_width = 1;// 词宽
			nextCharEquals = true;
			word = new StringBuilder();
			word.append(currentChar);
			/**
			 * 从当前字符之后的位置去寻找和这个当前字符相等的字符
			 */
			for (int tmpIndex = currentIndex + 2; tmpIndex < length; tmpIndex++) {
				tmpChar = charArray[tmpIndex];
				if (currentChar.equals(tmpChar)) {// 找到了和当前的这个字符相等的字符tmp
					while (nextCharEquals && tmpIndex + word_width < length) {
						currentCharNext = charArray[currentIndex + word_width];
						if (CommonConfig.PUNCTUATIONS.indexOf(currentCharNext) != -1) {// 标点符号
							break;//不需要再找了
						}
						tmpCharNext = charArray[tmpIndex + word_width];
						nextCharEquals = currentCharNext.equals(tmpCharNext);// 依次比较他们紧邻的字符是否相等
						if (nextCharEquals) {
							word.append(currentCharNext);
							word_width++;
						}
					}
					if (word.length() > 1) {// 文本中有相同的“词”
						_word = word.toString();
						if (words.containsKey(_word)) {
							Integer count = words.get(_word);
							count++;
							words.put(_word, count);
						} else {
							words.put(_word, 2);
						}
					}
					break; // 找到第一个以后就不再继续往下找
				}
			}
			currentIndex = currentIndex + word_width;// 这里也可以从当前字符的下一个开始
		}
		return words;
	}
}
